<?php

class DataWidget extends CWidget {

	public $template;
	public $data = array();
	
	public function init() {
		if(is_string($this->data))
			$this->data = Yii::app()->config->read($this->data);
		if(!$this->template)
			ob_start();
	}
	
	public function run() {
		if(!$this->template) {
			$viewContent = ob_get_contents();
			ob_end_clean();
			$viewFile = $this->getTempViewFile($viewContent);
		} else {
			$viewFile = $this->getOwner()->getViewFile($this->template);
		}
		$viewFile = $this->getOwner()->getViewFile($this->template);
		if(!viewFile) return;
		$dataProvider = $this->getDataProvider();
		$helper = new OutputHelper();
		
		$this->renderInternal($viewFile, array(
			'data' => $dataProvider,
		));
	}
	
	protected function getDataProvider() {
		$config = $this->data;
		if(!isset($config['class'])) {
			$model = $config['model'];
			unset($config['model']);
			$dataProvider = new CActiveDataProvider($model, $config);
		} else {
			$dataProvider = Yii::createComponent($config);
		}
		return $dataProvider;
	}
	
	protected function getTempViewFile(&$content) {
		$file = md5($content);
		$dir = Yii::getPathOfAlias('application.runtime.dataWidget.temp_views');
		@mkdir($dir, 0777);
		$filename = $dir.'/'.$file.'.php';
		return $filename;		
	}
	
}

?>